package microcredit.gui.action;

import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.io.File;

import javax.swing.ImageIcon;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.KeyStroke;
import javax.swing.SwingUtilities;
import javax.swing.filechooser.FileFilter;

import microcredit.db.Backup;
import microcredit.db.Factory;
import microcredit.gui.MainFrame;
import microcredit.gui.base.BaseAction;
import microcredit.gui.plaf.Extensions;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class ImportAction extends BaseAction {

	private static final long serialVersionUID = 1L;
	
	private static final Log LOGGER = LogFactory.getLog(ImportAction.class);
	
	public ImportAction(Component parent) {
		super(parent);
		putValue(NAME, "<html>Import <font size='-4'>(CTRL + I)</font>");
		putValue(SMALL_ICON, new ImageIcon(AboutAction.class.getResource("/microcredit/icons/x16/server_mail_upload.png")));
		putValue(ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_I, KeyEvent.CTRL_DOWN_MASK));
	}
	
	@Override
	public void perform(ActionEvent e) throws Throwable {
		Component parent = JOptionPane.getFrameForComponent((Component)e.getSource());
		
		JFileChooser chooser = new JFileChooser(defaultFolder);
		chooser.addChoosableFileFilter(new FileFilter() {
			@Override
			public String getDescription() {
				return "Import ZIP file. (*.zip)";
			}
			@Override
			public boolean accept(File f) {
				if (f.isDirectory()) {
					return true;
				}
				return f.getName().toLowerCase().endsWith(".zip");
			}
		});
		
		chooser.showDialog(parent, "Import");
		if (chooser.getSelectedFile() == null) {
			return;
		}
		
		String message = "There is already a version of the database installed.\n\nAre you sure you want to overwrite it?\n(A backup of old database will be created)";
		int option = JOptionPane.showConfirmDialog(parent, message);
		if (option == JOptionPane.YES_OPTION) {
			
			try {
				// create backup
				Backup.forcedBackup();
			} catch (Exception e2) {
				LOGGER.error(e2.getMessage(), e2);
				JOptionPane.showMessageDialog(parent, "Backup could not be created: \n"+e2.getMessage()+"\n\n The import has been stopped.", "Backup error", JOptionPane.ERROR_MESSAGE);
				return;
			}
			
			Factory.close(true);
			boolean ex = false;
			try {
				Factory.createImportExport().importDatabase(chooser.getSelectedFile());
				defaultFolder = chooser.getSelectedFile().getParentFile();
			} catch (Exception e1) {
				ex = true;
				LOGGER.error(e1.getMessage(), e1);
				JOptionPane.showMessageDialog(parent, "An error occured while importing the database: "+e1.getMessage(), "Error occured while importing.", JOptionPane.ERROR_MESSAGE);
			} finally {
				// restore connection
				Factory.initFactoryNew();
			}
			if (!ex) {
				JOptionPane.showMessageDialog(parent, "Database sucessfully imported from "+chooser.getSelectedFile());
			}
			if (parent instanceof MainFrame) {
				((MainFrame) parent).getController().refreshCurrentSelector();
			}
		}
	}
	
}